package com.yq.testmodule.textalign

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import android.view.View.MeasureSpec.EXACTLY
import android.widget.FrameLayout
import android.widget.TextView

class TextWithMoreWrapper @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {

    lateinit var textView: TextView
    lateinit var moreView: View

    override fun onFinishInflate() {
        super.onFinishInflate()
        textView = getChildAt(0) as TextView
        moreView = getChildAt(1)
    }

    @SuppressLint("Range")
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //测量完成后，需要判断父容器的高度是否需要调整
//        1. 获取Textview最后一个字所在的x位置，加上 moreview的宽度
        val index = textView.text.trim().length
        val layout = textView.layout
        val bound = Rect()
        val line = layout.getLineForOffset(index)
        layout.getLineBounds(line, bound);
        val xAxisRight = layout.getSecondaryHorizontal(index) //字符右边x坐标

        if(moreView.measuredWidth + xAxisRight > measuredWidth){
            val height = MeasureSpec.makeMeasureSpec(
                View.MeasureSpec.EXACTLY,
                textView.measuredHeight + moreView.measuredHeight
            )
            setMeasuredDimension(measuredWidth,textView.measuredHeight + moreView.measuredHeight)
        }

        //2. 超出父容器的最大高度，则调整父容器高度,否则，在布局过程讲moreview直接布局在textview最后一个字后面即可

    }

    @SuppressLint("Range")
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        //布局完成后再重新调整 查看更多的位置
        val index = textView.text.trim().length
        val layout = textView.layout
        val bound = Rect()
        val line = layout.getLineForOffset(index)
        layout.getLineBounds(line, bound);
        val xAxisRight = layout.getSecondaryHorizontal(index) //字符右边x坐标

        if(moreView.measuredWidth + xAxisRight > measuredWidth){
           moreView.layout(0,bound.bottom,moreView.measuredWidth,bound.bottom+moreView.measuredHeight)
        }else{
            moreView.layout(xAxisRight.toInt(),bound.top,xAxisRight.toInt()+moreView.measuredWidth,bound.top+moreView.measuredHeight)
        }
    }
}